#include "tracimportwizard.h"
#include "tracvalidationpage.h"
#include "tracimportprojectselectionpage.h"
#include "tracimportsettingspage.h"
#include "tracsettings.h"


#include "vcsbase/checkoutjobs.h"

#include <utils/qtcassert.h>

#include <QtGui/QIcon>
#include <QSharedPointer>

namespace Trac {
namespace Internal {

TracImportWizard::TracImportWizard(QObject *parent)
    : VCSBase::BaseCheckoutWizard(parent)
{
    setId("TracRepository");
}

TracImportWizard::~TracImportWizard()
{
    TracSettings::instance()->~TracSettings();
}

QIcon TracImportWizard::icon() const
{
    return QIcon();
}

QString TracImportWizard::description() const
{
    return tr("Import a trac project into Qt Creator.");
}

QString TracImportWizard::displayName() const
{
    return tr("Trac Project Import");
}

QList<QWizardPage *> TracImportWizard::createParameterPages(const QString &path)
{
    TracValidationPage *page1 = new TracValidationPage();
    TracImportProjectSelectionPage *page2 = new TracImportProjectSelectionPage(page1);
    TracImportSettingsPage *page3 = new TracImportSettingsPage(page2);
    TracSettings::instance()->setWorkingPath(path);

    QList<QWizardPage *> pages;
    return pages << page1 << page2 << page3;
}

QSharedPointer<VCSBase::AbstractCheckoutJob> TracImportWizard::createJob(
        const QList<QWizardPage *> &parameterPages, QString *checkoutPath)
{
    return createCheckoutJob(checkoutPath);
}


QSharedPointer<VCSBase::AbstractCheckoutJob> TracImportWizard::createCheckoutJob(QString *checkoutPath) const
{
    TracSettings *importSettings = TracSettings::instance();
    const QString workingDirectory = importSettings->workingPath();
    const QString checkoutDir = importSettings->checkoutDirectory();

    *checkoutPath = workingDirectory + QLatin1Char('/') + checkoutDir;

    const QString binary = importSettings->binary();

    VCSBase::ProcessCheckoutJob *job = new VCSBase::ProcessCheckoutJob;
    const QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); //client->processEnvironment();

    // 1) Basic checkout step
    QStringList args;

    args << importSettings->cloneCommand() << importSettings->cloneUrl() << checkoutDir;

    if(binary == "svn") {
        QStringList svnArgs;
        svnArgs.push_back(QLatin1String("--username"));
        svnArgs.push_back(importSettings->username());
        svnArgs.push_back(QLatin1String("--password"));
        svnArgs.push_back(importSettings->password());
        svnArgs.append(args);
        args = svnArgs;
    }

    job->addStep(binary, args, workingDirectory, env);

    //TODO: branch

    return QSharedPointer<VCSBase::AbstractCheckoutJob>(job);
}


} // namespace Internal
} // namespace Trac
